import { __private, _decorator, Button, Color, Component, EventTouch, Graphics, instantiate, Label, Node, Prefab, resources, Sprite, SystemEvent, tween, Tween, UITransform, v2, v3, Vec2 } from 'cc';
import BaseView from '../../../platform/ui/BaseView';
import { Game_2048_MergeDirection, Game_Level_Names, Game_Levels, Game_Status, Menu_Btns, ViewLayerDefine } from '../../common/enums';
import { ResManager } from '../../../platform/resources/ResMgr';
import { bind, uiview } from '../../../platform/ui/UIDecorator';
import { watch } from '@vue/reactivity';
import { LogMgr } from '../../../platform/log/LogMgr';
import { TbRoot } from '../../../platform/excel_table/TbRoot';
import { Tb_GameList, Tb_GameListContainer } from '../../tb/Tb_GameList';
import UIMgr from '../../../platform/ui/UIMgr';
import { game2048_cellColors } from '../../static_config';
import { PlayerData } from '../../data/player/PlayerData';
import { GameWuziqiModel } from './GameWuziqiModel';
import { GameWuziqiCtl } from './GameWuziqiCtl';
import { Chess } from './Chess';
import { WuziqiBoard } from './WuziqiBoard';
const { ccclass, property } = _decorator;





@uiview({
    prefabPath:"prefab/ui/wuziqi/GameWuziqiPlayView",
    layer:ViewLayerDefine.Pop,
    dataModel:GameWuziqiModel,
    controller:GameWuziqiCtl,
    single:true
})
@ccclass('GameWuziqiPlayView')
export class GameWuziqiPlayView extends BaseView<GameWuziqiModel,GameWuziqiCtl> {
    //#region 节点绑定
    @bind(Label)
    title:Label = null

    @bind(Node)
    back:Node = null
    @bind(Node)
    rule:Node = null
    @bind(Node)
    rule_tips:Node = null
    @bind(Node)
    share:Node = null
    @bind(Node)
    volumn:Node = null

    @bind(Node)
    endPanel:Node = null
    @bind(Node)
    stastics:Node = null
    @bind(Node)
    end_sure:Node = null

    @bind(Label)
    nowPoint:Label = null
    @bind(Label)
    maxPoint:Label = null

    @bind(Node)
    board:Node = null
    @bind(Node)
    board_bg:Node = null
    @bind(Node)
    chesses:Node = null

    @bind(Button)
    restart:Button = null
    //#endregion
    cfg:Tb_GameList = null
    level:number = 0
    touchStartPos : { x:number, y: number } |null= null;
    gap:number = 0
    chessW:Prefab = null
    chessB:Prefab = null
    nowChess:string = "black"
    aiChessTween:Tween<Node> = null

    protected init(): void {

        //得分

        //按钮
        this.initBtns()
        this.initLevels()

    }
    initLevels() {

    }
    initBtns() {
        this.back.on(Button.EventType.CLICK, this.onBackClick, this)
        this.volumn.on(Button.EventType.CLICK, this.onVolumnClick, this)
        this.share.on(Button.EventType.CLICK, this.onShareClick, this)
        this.rule.on(Button.EventType.CLICK, this.onRuleClick, this)
        this.restart.node.on(Button.EventType.CLICK, this.onRestartClick, this)
        this.rule_tips.on(Button.EventType.CLICK, this.onRuleTipsClick, this)

        this.board.on(SystemEvent.EventType.TOUCH_START, this.onTouchStart, this);
        this.board.on(SystemEvent.EventType.TOUCH_END, this.onTouchEnd, this);
        this.board.on(SystemEvent.EventType.TOUCH_CANCEL, this.onTouchEnd, this);

    }

    onTouchStart(event: EventTouch){
        // if(this.dataModel.gameState != Game_Status.Playing) return;
        if(this.touchStartPos) {
            //TODO tips组件通用化
            // UIMgr.ins.tips("操作太快了，请稍后再试试");
            return
        }
        let worldPos = event.getUILocation();
        let localPos = v3()
        //世界坐标转为局部坐标
        this.node.inverseTransformPoint(localPos,v3(worldPos.x,worldPos.y))

        this.touchStartPos = { x: localPos.x, y: localPos.y+30 };
    }
    onTouchEnd(event: EventTouch){
        if (!this.touchStartPos) return;
        if(this.dataModel.board.gameOver){
            UIMgr.ins.showTips("对局已结束！")
            return
        }
        let currentPlayer = this.dataModel.board.currentPlayer
        if(currentPlayer!=1){
            this.touchStartPos = null
            UIMgr.ins.showTips("还没轮到你！")
            return
        }
        // LogMgr.debug("点击节点的坐标为：",this.touchStartPos)
        let chesses = this.dataModel.board.board
        let clickChess:Chess|null = null;
        for (let index = 1; index <= 16; index++) {
            for (let j = 1; j <= 16; j++) {
                let element = chesses[index][j];
                let distance = Vec2.distance(this.touchStartPos,v2(element.x,element.y))
                if(distance<=this.gap/2){
                    clickChess = element
                    this.dataModel.board.makeMove(index,j,currentPlayer,()=>{
                        ResManager.inst.loadBundleRes("resources/prefab/ui/wuziqi/chess_b",Prefab).then(prefab=>{
                            let chessIns = instantiate(prefab) as Node
                            chessIns.setPosition(clickChess.x,clickChess.y)
                            this.chesses.addChild(chessIns)
                       }).catch(e=>{
                            LogMgr.err("加载棋子预制件失败！")
                       })
                        // if(currentPlayer===2){
                        //     this.nowChess = "white"
                        //     ResManager.inst.loadBundleRes("resources/prefab/ui/wuziqi/chess_b",Prefab).then(prefab=>{
                        //         let chessIns = instantiate(prefab) as Node
                        //         chessIns.setPosition(clickChess.x,clickChess.y)
                        //         this.chesses.addChild(chessIns)
                        //         clickChess.status = 1
                        //    }).catch(e=>{
                        //         LogMgr.err("加载棋子预制件失败！")
                        //    })
                        // }else{
                        //     this.nowChess = "black"

                        // }
                    })
                    break
                }
            }
        }
        this.touchStartPos = null
        if(this.dataModel.board.gameOver){
            return
        }
        //AI走
        let pos = this.dataModel.ai.getMove(this.dataModel.board)
        this.dataModel.board.makeMove(pos[0],pos[1],this.dataModel.board.currentPlayer,()=>{
            ResManager.inst.loadBundleRes("resources/prefab/ui/wuziqi/chess_w",Prefab).then(prefab=>{
                let chessIns = instantiate(prefab) as Node
                let moveChess = this.dataModel.board.board[pos[0]][pos[1]]
                chessIns.setPosition(moveChess.x,moveChess.y)
                this.chesses.addChild(chessIns)
                //动画
                if(this.aiChessTween){
                    this.aiChessTween.stop()
                    let targe = this.aiChessTween.getTarget()
                    if(targe){
                        targe.setScale(1,1,1)
                    }
                }
                this.aiChessTween = tween(chessIns)
                .to(0.1,{scale:v3(1.2,1.2,1)})
                .to(0.1,{scale:v3(1,1,1)})
                .union()
                .repeat(2)
                .start()
           }).catch(e=>{
                LogMgr.err("加载棋子预制件失败！")
           })
        })
    }

    protected show(...args: any[]): void {
        this.cfg = this.showArgs[0]
        this.level = this.showArgs[1]
        //标题
        this.title.string = this.cfg.name+"-"+Game_Level_Names[this.level]
        // if(this.chessW==null){
        //     let result = await ResManager.inst.loadBundleRes("resources/prefab/ui/wuziqi/chess_b",Prefab)
        // }
        //重新初始化游戏？
        //TODO 先从本地读取数据
        this.loadLocalData()
        this.drawBoardBg()
        //棋盘棋子生成
    }
    drawBoardBg() {
        let gragh = this.board_bg.getComponent(Graphics)
        if(!gragh){
            gragh = this.board_bg.addComponent(Graphics)
        }
        let uicmp = this.board_bg.getComponent(UITransform)
        let width = uicmp.width
        let height = uicmp.height
        let gap = width/17
        this.gap = gap
        gragh.clear()
        gragh.lineWidth = 2;
        //计算原点，棋盘左上角开始
        let zeroX = -width/2
        let zeroY = height/2
        LogMgr.debug("zero point:",zeroX,zeroY)
        gragh.moveTo(zeroX, zeroY);
        //计算棋盘得放置点
        let chesses = this.dataModel.board.board
        for (let i = 1; i <= 16; i++) {
            for (let j = 1; j <= 16; j++) {
                let chessX = zeroX+gap*j;
                let chessY = zeroY-gap*i;
                let chess = chesses[i][j]
                chess.x = chessX
                chess.y = chessY
            }
        }

        //画竖线
        for (let i = 1; i <= 16; i++) {
            gragh.moveTo(zeroX+gap*i, zeroY-gap);
            gragh.lineTo(zeroX+gap*i, zeroY-height+gap);
        }
        //画横线
        for (let i = 1; i <= 16; i++) {
            gragh.moveTo(zeroX+gap, zeroY-gap*i);
            gragh.lineTo(zeroX+width-gap, zeroY-gap*i);
        }
        gragh.stroke()
        //画点
        gragh.fillColor = Color.BLACK
        gragh.arc(zeroX+gap*6,zeroY-gap*6,6,0,360,true)
        gragh.fill()

        gragh.arc(zeroX+gap*11,zeroY-gap*6,6,0,360,true)
        gragh.fill()

        gragh.arc(zeroX+gap*6,zeroY-gap*11,6,0,360,true)
        gragh.fill()

        gragh.arc(zeroX+gap*11,zeroY-gap*11,6,0,360,true)
        gragh.fill()
        // gragh.moveTo(0, 0);
        // gragh.lineTo(width/2, 0);


    }

    protected getModelKey(): string {
        return this.cfg.name+"_"+this.level
    }
    loadLocalData() {
        let key = this.getModelKey()
        ezgame.info("modelkey:"+key)
        let levelLocalDataStr = localStorage.getItem(key)
        if(levelLocalDataStr){
            this.dataModel.resetData(JSON.parse(levelLocalDataStr))
        }else{
            this.dataModel.board = new WuziqiBoard(16)
        }
        
    }

    protected close() {
        // this.back.off(Button.EventType.CLICK, this.onBackClick, this)
        //数据存盘
        localStorage.setItem(this.getModelKey(),JSON.stringify(this.dataModel))
    }


    //#region

    onBackClick(){
                //判断游戏是否进行中，二次确认退出
        // UIMgr.ins.closeUI(Game2048PlayView)
        //TODO 记录状态信息到本地
        ezgame.ui.closeUI(this)
    }
    onVolumnClick(){
        LogMgr.info("音量开关")
    }
    onShareClick(){
        LogMgr.info("点击分享")
    }
    onRuleClick(){
        LogMgr.info("点击规则按钮")
        this.rule_tips.active = true
    }
    onRestartClick(){
        LogMgr.info("点击重新开始按钮")
    }
    onRuleTipsClick(){
        this.rule_tips.active = false
    }
}



